#encoding: utf-8
class GroupsThread < ActiveRecord::Base
  has_many :groups_posts, :dependent => :delete_all
  has_many :thread_visits, {:foreign_key => :thread_id, :dependent => :delete_all}
  has_many :feeds, {:as => :content, :dependent => :delete_all}

  belongs_to :group
  belongs_to :member
  
  validates_length_of :title, :minimum => 3
  validates_presence_of :content
  
  before_create :generate_slug
  
  def generate_slug
  	slug = self.title.downcase
  	slug.gsub!('š','s')
  	slug.gsub!('đ','d')
  	slug.gsub!('č','c')
  	slug.gsub!('ć','c')
  	slug.gsub!('ž','z')
  	slug.gsub!(/[^a-z0-9\s]/, '') 
  	slug.gsub!(/\s+/,'-')
  	self.slug = slug
  end
  
  def recount
    self.post_count = self.groups_posts.length
    self.save
  end
  
  def visit (member)
    
    return if member.nil?
    
    current_thread_visit = member.thread_visits.where(:thread_id => self.id).first

      # ako jos nema unosa u bazu
      if current_thread_visit == nil
        thread_visit = ThreadVisit.new
        thread_visit.member_id = member.id
        thread_visit.thread_id = self.id
        thread_visit.save
      else
        current_thread_visit.updated_at = Time.now
        current_thread_visit.save
      end  
  end
  
  def url
  	return '/tema/'+id.to_s+'/'+group.slug+'/'+slug
  end
  


end
